#include "dominion.h"
#include "dominion_helpers.h"
#include "rngs.h"
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include <math.h>

#define DEBUG 0
#define NOISY_TEST 1

int checkSmithy(int p, int currPlayer, int handPos, struct gameState *post)
{
	int r, hand, played;
	hand = post->handCount[currPlayer];
	played = post->playedCardCount;
	r = playCard(handPos, -1, -1, -1, post);
	if (r != 0) {
		printf("Failed to play card.\n");
		return r;
	}
	//Tests:
	//Player gained two cards
	if (post->handCount[currPlayer] != hand + 2) {
		printf("Hand count mismatch. Expected:%d  Result:%d\n", 
		       hand+2, post->handCount[currPlayer]);
		r--;
	}
	//One more card on played pile
	if (post->playedCardCount != played + 1) {
		printf("Played count mismatch. Expected:%d  Result:%d\n",
		       played+1, post->playedCardCount);
		r--;
	}
	//Most recent played card is smithy
	if (post->playedCards[post->playedCardCount - 1] != smithy) {
		printf("Smithy not in played cards correctly. Actual:%d\n",
		       post->playedCards[post->playedCardCount - 1]);
		r--;
	}
	return r;
}

int main()
{
	int i, n, p, currPlayer, handPos;
	int k[10] = {adventurer, council_room, feast, gardens, mine,
	             remodel, smithy, village, baron, great_hall};
	
	printf("SMITHY RANDOM TESTS BEGIN:\n");
	
	SelectStream(2);
	PutSeed(3);
	struct gameState G;
	
	for(n = 0; n < 2000; n++) {
		for (i = 0; i < sizeof(struct gameState); i++) {
			((char*)&G)[i] = floor(Random() * 256);
		}

		//p = floor(Random() * 4) + 2;
		p = 4;
	    
		int r = initializeGame(p, k, 1, &G);
	    if (r != 0)
		    printf("Failed to initialize game state!\n");
	    
	    currPlayer = floor(Random() * p);
		G.whoseTurn = currPlayer;
		G.deckCount[currPlayer] = floor(Random() * MAX_DECK);
		G.discardCount[currPlayer] = floor(Random() * MAX_DECK);
		G.handCount[currPlayer] = floor(Random() * MAX_HAND);

		for (i = 0; i < G.handCount[currPlayer]; i++) {
			int kn = floor(Random() * 10);
			G.hand[currPlayer][i] = k[kn];
		}
    
		handPos = floor(Random() * G.handCount[currPlayer]);
		G.hand[currPlayer][handPos] = smithy;

		checkSmithy(p, currPlayer, handPos, &G);
	}
	
	printf("ALL RANDOM TESTS PASSED.\n");
	return 0;
}
